//
//  HMUserAccountViewModel.swift
//  iOSWeibo12
//
//  Created by Admin on 16/9/11.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

/// 专门处理HMUserAccount的相关操作
class HMUserAccountViewModel: NSObject {
    // 单例
    static let shared = HMUserAccountViewModel()
    
    /// 归档路径
    var accountPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! as String + "/userAccount.plist"
    
    /// 私有化构造函数
    private override init() {
        super.init()
        
        userAccount = loadUserAccount()
    }
    
    /// 用户账号,保存AccessToken,以后程序中要使用 HMUserAccount, 都访问它(userAccount)
    var userAccount: HMUserAccount?
    
    /// 用户是否登录
    /// 计算性属性,只提供get方法
    var userLogin: Bool {
        // 有账号返回true,没有账号返回false
        return userAccount != nil
    }
    
    // MARK: - 加载Access Token
    func loadAccessToken(code: String, completion: @escaping (Error?) -> Void) {
        // api地址
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        // post 参数
        let parameters = [
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirect_uri
        ]
        
        HMNetworkTool.shared.request(method: HMNetworkMethod.POST, URLString: urlString, parameters: parameters, progress: nil, success: { (_, result) in
            print("result = \(result)")
            let dict = result as! [String: Any]
            
            // 字典转模型
            self.userAccount = HMUserAccount(dict: dict)
            print("userAccount = \(self.userAccount)")
            self.saveUserAccount()
            
            // 调用闭包,完成accessToken加载和保存
            completion(nil)
        }) { (_, error) in
            // 调用闭包,加载accessToken出错了
            completion(error)
        }
    }
    
    /**
     加载用户信息
     - parameter loadUserInfoCallBack: 回调
     */
    func loadUserInfo(completion: @escaping (Error?) -> ()) {
        // 判断access_token
        guard let access_token = userAccount?.access_token else {
            print("access_token为空")
            return
        }
        
        // 判断uid
        guard let uid = userAccount?.uid else {
            print("uid为空")
            return
        }
        
        // 5.url
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        // 6.准备参数
        let parameters = ["access_token": access_token, "uid": uid]
        
        HMNetworkTool.shared.request(method: .GET, URLString: urlString, parameters: parameters, progress: nil, success: { (_, result) in
            
            let dict = result as? [String: Any]
            
            // 获取数据
            self.userAccount?.screen_name = dict?["screen_name"] as? String
            self.userAccount?.avatar_large = dict?["avatar_large"] as? String
            
            // 保存起来
            self.saveUserAccount()
            
            // 执行闭包
            completion(nil)
            
            }) { (_, error) in
                completion(error)
        }
    }
    
    ///  保存账户信息
    private func saveUserAccount() {
        if userAccount != nil {
            NSKeyedArchiver.archiveRootObject(userAccount!, toFile: accountPath)
        }
    }
    
    /**
     从沙盒里面加载用户账号
     returns: 之前保存的用户账号
     */
    private func loadUserAccount() -> HMUserAccount? {
        // 从沙盒里面解档账号
        let account = NSKeyedUnarchiver.unarchiveObject(withFile: accountPath) as? HMUserAccount
        
        // 解档并不一定能解档出
        // 判断账号是有在有效期内
//        account?.expiresDate = Date(timeIntervalSinceNow: -100)
        if account != nil && account?.expiresDate?.compare(Date()) == ComparisonResult.orderedDescending {
            print("加载到有效的账号: \(account)")
            
            return account
        }
        
        // 没有加载到可用账号
        return nil
    }
}
